﻿namespace WebSilverlight.Controls
{    
    using System.Collections.ObjectModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using WebSilverlight.Helpers;    

    public partial class PictureControl : ChildWindow
    {
        #region Properties
            CaptureSource _captureSource;
            ObservableCollection<WriteableBitmap> _images = new ObservableCollection<WriteableBitmap>();
            public WriteableBitmap Current { get; set; }
            public bool SelectionChanged { get; set; }
        #endregion

        public PictureControl()
        {
            InitializeComponent();
            SelectionChanged = false;
            Loaded += new RoutedEventHandler(Page_Loaded);
        }

        void Page_Loaded(object sender, RoutedEventArgs e)
        {            
            // get list of the video sources
            VideoSources.ItemsSource = CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();

            if (VideoSources.Items.Count == 0)
            {
                //this.ControlContent.Visibility = System.Windows.Visibility.Collapsed;
                //this.SourcesExpander.IsExpanded = false;
                //this.SourcesExpander.IsEnabled = false;
                this.btn_StartCapture.IsEnabled = false;
                this.ControlError.Visibility = System.Windows.Visibility.Visible;
                this.CameraActions.Visibility = System.Windows.Visibility.Collapsed;
                this.ErrorText.Text = "No available Video Source";
            }

            // creating a new capture source
            _captureSource = new CaptureSource();
            // wire up the async image capture for snapshot
            _captureSource.CaptureImageCompleted += ((s, args) =>
            {
                _images.Add(args.Result);
            });

            // bind snapshot images
            Snapshots.ItemsSource = _images;

            // Loads the Current Image
            if (Current != null)
            {
                ImageBrush imgBrush = new ImageBrush();
                imgBrush.ImageSource = Current;
                WebcamCapture.Fill = imgBrush;
                _images.Add(Current);
            }
        }

        private void CaptureButton_Click(object sender, RoutedEventArgs e)
        {
            StartCapture();
        }
        private void VideoSource_Selected(object sender, SelectionChangedEventArgs e)
        {
            StartCapture();
        }

        private void StopCapture_Click(object sender, RoutedEventArgs e)
        {
            StopCapture();
        }

        private void TakeSnapshot_Click(object sender, RoutedEventArgs e)
        {
            if (_captureSource != null)
            {
                // capture the current frame and add it to our observable collection                
                _captureSource.CaptureImageAsync();
            }
        }
        
        private void StopCapture()
        {
            if (_captureSource != null && VideoSources.Items.Count > 0)
            {
                _captureSource.Stop();
                this.btn_StartCapture.IsEnabled = true;
                this.btn_StopCapture.IsEnabled = false;
                this.btn_TakeSnapshot.IsEnabled = false;
            }
        }

        private void StartCapture()
        {
            if (_captureSource != null)
            {
                if (VideoSources.SelectedItems.Count != 1)
                {
                    System.Windows.MessageBox.Show("Select a Video Source");
                }
                else
                {
                    this.btn_StartCapture.IsEnabled = false;
                    this.btn_StopCapture.IsEnabled = true;
                    this.btn_TakeSnapshot.IsEnabled = true;

                    _captureSource.Stop(); // stop whatever device may be capturing

                    // set the devices for the capture source
                    _captureSource.VideoCaptureDevice = (VideoCaptureDevice)VideoSources.SelectedItem;

                    // create the brush
                    VideoBrush vidBrush = new VideoBrush();
                    vidBrush.SetSource(_captureSource);
                    WebcamCapture.Fill = vidBrush; // paint the brush on the rectangle

                    // request user permission and display the capture
                    if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess())
                    {
                        _captureSource.Start();
                    }
                }
            }
        }

        private void SaveSnapshot_Click(object sender, RoutedEventArgs e)
        {
            StopCapture();
            this.DialogResult = true;
            this.Close();
        }

        private void Snapshot_Selected(object sender, SelectionChangedEventArgs e)
        {
            if (this.Snapshots.SelectedItems.Count == 1)
            {
                Current = (WriteableBitmap)this.Snapshots.SelectedItem;
                SelectionChanged = true;
                this.btn_SaveSnapshot.IsEnabled = true;

                StopCapture();
                
                ImageBrush imgBrush = new ImageBrush();
                imgBrush.ImageSource = Current;
                WebcamCapture.Fill = imgBrush;
            }
        }

        private void UpLoad_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Jpeg Files (.jpg)|*.jpg|Bmp Files (.bmp)|*.bmp|Png Files (.png)|*.png|All Files (.*)|*.*";
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog().Value)
            {
                using (System.IO.Stream srcStream = openFileDialog.File.OpenRead())
                {
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(srcStream);                                        
                    WriteableBitmap bmp = new WriteableBitmap(bitmapImage);
                    _images.Add(bmp);                    
                }
            }
        }        
    }
}